package com.ujs.edu.medicine.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.qiniu.util.Auth;
import com.ujs.edu.medicine.dao.*;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.Result;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:
 * @Date: Created in 14:07 2020/8/25
 * Description: 帖子控制类
 * Modified By:
 */
@RestController
public class PostController {

    @Autowired
    YunjiayiPostMapper yunjiayiPostMapper;
    @Autowired
    YunjiayiLikeMapper yunjiayiLikeMapper;
    @Autowired
    YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    YunjiayiCommentMapper yunjiayiCommentMapper;
    @Autowired
    PictureMSMapper pictureMSMapper;
    @Autowired
    TablePostMesMapper tablePostMesMapper;
    @Autowired
    TableConsultDUMapper tableConsultDUMapper;

    @Autowired
    private HttpServletRequest request;

    public String gettoken(){
        return request.getHeader("Authorization");
    }

    /*帖子列表*/
    @RequestMapping("/api/post/list")
    public Result postlist(@RequestParam(value = "userID", required = false) Integer uId, @RequestParam(value = "page", required = false) Integer page) {
        Result result = new Result();

        if (uId != null) {
            List<YunjiayiPost> posts = yunjiayiPostMapper.getPostByuId(uId);
            if (posts != null) {
                for (YunjiayiPost post:posts){
                    post.setAuthor(yunjiayiUserMapper.selectPartInfo(post.getUserid()));
                    post.setComment_num(Integer.toString(yunjiayiCommentMapper.countCommenyNum(post.getPostId())));
                    post.setLike_num(Integer.toString(yunjiayiLikeMapper.countLikeNum(post.getPostId())));
                }
                result.setCode(0);
                result.setMessage("查询成功");
                result.setData(posts);
            } else {
                result.setCode(1);
                result.setMessage("失败");
            }
        } else if (page != null) {
            if (page<=0){
                result.setCode(1);
                result.setMessage("查询失败");
            }
            Integer startIndex = (page - 1) * 10;
            Integer pageSize = 10;
            List<YunjiayiPost> posts = yunjiayiPostMapper.selectLimit(startIndex, pageSize);
            if (posts != null) {
                for (YunjiayiPost post:posts){
                    post.setAuthor(yunjiayiUserMapper.selectPartInfo(post.getUserid()));
                    post.setComment_num(Integer.toString(yunjiayiCommentMapper.countCommenyNum(post.getPostId())));
                    post.setLike_num(Integer.toString(yunjiayiLikeMapper.countLikeNum(post.getPostId())));
                }
                result.setCode(0);
                result.setMessage("查询成功");
                result.setData(posts);
            } else {
                result.setCode(1);
                result.setMessage("查询失败");
            }
        }

        return result;
    }


    /*帖子具体信息*/
    @RequestMapping("/api/post/getPostDetail")
    public Result getPostDetail(@RequestParam("id") Integer postId) {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            myuserid=0;
        }

        YunjiayiPost post = yunjiayiPostMapper.selectByPrimaryKey(postId);
        if (post != null) {
            post.setAuthor(yunjiayiUserMapper.selectPartInfo(post.getUserid()));
            post.setLike_num(Integer.toString(yunjiayiLikeMapper.countLikeNum(post.getPostId())));
            if (myuserid!=0){
                YunjiayiLike like=yunjiayiLikeMapper.getLikeByUidpostId(post.getPostId(),myuserid);
                if (like!=null){
                    post.setIsLike(true);
                }else {
                    post.setIsLike(false);
                }
            }else {
                post.setIsLike(false);
            }

            YunjiayiPost post1=yunjiayiPostMapper.selectBypostAndUs(myuserid,post.getPostId());
            if (post1!=null){
                post.setIsMy(true);
            }else {
                post.setIsMy(false);
            }
            //?帖子是否被接单
            //图片files数组
            List<String> files=pictureMSMapper.selectByPostId(post.getPostId());
            post.setFiles(files);
            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(post);
        } else {
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }

    /*增加帖子*/
    @RequestMapping("/api/post/addPost")
    public Result addPost(@RequestBody JSONObject object) {
        Result result = new Result();
        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        } catch (Exception  e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登录");
            return result;
        }

        YunjiayiPost post1=new YunjiayiPost();

        post1.setContent(object.getString("content"));
        post1.setUserid(myuserid);
        post1.setLikeid(0);
        post1.setCommitid(0);

        int addpost = yunjiayiPostMapper.insert(post1);
        PictureMS pictureMS=new PictureMS();
        List<String>files=object.getJSONArray("files").toJavaList(String.class);
        for (String file:files){
            pictureMS.setPictureurl(file);
            pictureMS.setPostid(post1.getPostId());
            Integer addp=pictureMSMapper.insert(pictureMS);
            if (addp!=1){
                result.setCode(1);
                result.setMessage("上传文件失败");
                return result;
            }
        }
        if (addpost == 1) {
            result.setCode(0);
            result.setMessage("添加成功");
        } else {
            result.setCode(1);
            result.setMessage("添加失败");
        }

        return result;
    }


    /*删除帖子*/
    @RequestMapping("/api/post/deletePost")
    public Result deletePost(@RequestBody Map<String,Integer> map) {
        Result result = new Result();

        int deletepos = yunjiayiPostMapper.deleteByPrimaryKey(map.get("id"));
        int delpic=pictureMSMapper.deleteByPostId(map.get("id"));
        System.out.println(delpic);
        if (deletepos == 1&&delpic!=0) {
            result.setCode(0);
            result.setMessage("删除成功");
        } else {
            result.setCode(1);
            result.setMessage("删除失败");
        }

        return result;
    }


    /*修改帖子*/
    @RequestMapping("/api/post/updatePost")
    public Result updatePost(@RequestBody JSONObject object) {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还未登陆，请登陆");
            return result;
        }

        YunjiayiPost post1=yunjiayiPostMapper.selectByPrimaryKey(object.getInteger("postId"));

        post1.setContent(object.getString("content"));


        int updatepos = yunjiayiPostMapper.updateByPrimaryKey(post1);

        int delpict=pictureMSMapper.deleteByPostId(post1.getPostId());
        PictureMS pictureMS=new PictureMS();
        for (String file:object.getJSONArray("files").toJavaList(String.class)){
            pictureMS.setPictureurl(file);
            pictureMS.setPostid(post1.getPostId());
            int ins=pictureMSMapper.insert(pictureMS);
            if (ins==0){
                result.setCode(1);
                result.setMessage("插入图片失败");
                return result;
            }
        }
        if (updatepos == 1) {
            result.setCode(0);
            result.setMessage("修改成功");
        } else {
            result.setCode(1);
            result.setMessage("修改失败");
        }

        return result;
    }


    /*点赞/取消点赞*/
    @RequestMapping("/api/post/like")
    public Result postLike(@RequestBody JSONObject object) {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还未登陆，请登陆");
            return result;
        }


        YunjiayiLike like = yunjiayiLikeMapper.getLikeByUidpostId(object.getInteger("post_id"),myuserid);

        if (like != null) {
            int delpos=yunjiayiLikeMapper.deleteByPrimaryKey(like.getLikeid());
            System.out.println(delpos!=0);
            if (delpos!=0){
                result.setCode(0);
                result.setMessage("取消点赞成功");
            }else {
                result.setCode(1);
                result.setMessage("取消点赞失败");
            }
            return result;
        }

        like=new YunjiayiLike();
        like.setPostid(object.getInteger("post_id"));
        like.setUserid(myuserid);
        int li = yunjiayiLikeMapper.insert(like);
        if (li == 1) {
            result.setCode(0);
            result.setMessage("点赞成功");
        } else {
            result.setCode(1);
            result.setMessage("点赞失败");
        }

        return result;
    }


    /*接单*/
    @RequestMapping("/api/post/catche")
    public Result catche(@RequestParam("postId") Integer postId) {
        Result result = new Result();


        return result;
    }


    /*帖子消息列表*/
    //当有人给你的帖子评论或点赞的时候会提示
    @RequestMapping("/api/message/post")
    public Result postInfo(){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid= JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还未登陆，请登陆");
            return result;
        }

        List<TablePostMes> tablePostMess=tablePostMesMapper.selectBytouserId(myuserid);

        try {
            for (TablePostMes tablePostMes:tablePostMess){
                tablePostMes.setAuthor(yunjiayiUserMapper.selectPartInfo(tablePostMes.getFromuserid()));
                tablePostMes.setAbstracttest(tablePostMes.getContent());
            }
            result.setCode(0);
            result.setMessage("获取成功");
            result.setData(tablePostMess);
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("获取失败");
        }

        return result;
    }



    /*通过会诊id获取会诊具体信息*/
    @RequestMapping(value = "/api/message",method = RequestMethod.GET)
    public Result gePostInfo(@RequestParam("messageID")Integer messageID){
        Result result=new Result();
        JSONObject object=new JSONObject();
        Author author=new Author();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        try {
            TableConsultDU tableConsultDU=tableConsultDUMapper.selectByPrimaryKey(messageID);

            author=yunjiayiUserMapper.selectPartInfo(tableConsultDU.getFromuserid());

            object.put("author",author);
            object.put("createTime",tableConsultDU.getCreatetime());
            object.put("content",tableConsultDU.getContent());
            object.put("files",JSONObject.parseArray(tableConsultDU.getFiles()));

            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(object);
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("查询失败");
        }



        return result;
    }


    /*移除通知、帖子或会诊消息*/
    @RequestMapping(value = "/api/message",method = RequestMethod.DELETE)
    public Result delInfo(@RequestBody JSONObject object){

        Result result=new Result();

        if (object.getInteger("type")==1){
            //通知
            int delnotice=yunjiayiPostMapper.deleteByPrimaryKey(object.getInteger("id"));
            if (delnotice!=0){
                result.setCode(0);
                result.setMessage("删除通知成功");
            }else {
                result.setCode(1);
                result.setMessage("删除通知失败，检查是否有这个消息");
            }
        }else if (object.getInteger("type")==2){
            //帖子
            int delpost=tablePostMesMapper.deleteByPrimaryKey(object.getInteger("id"));
            if (delpost!=0){
                result.setCode(0);
                result.setMessage("删除帖子成功");
            }else {
                result.setCode(1);
                result.setMessage("删除帖子失败，检查是否有这个消息");
            }
        }else if (object.getInteger("type")==3){
            int delconsult=tableConsultDUMapper.deleteByPrimaryKey(object.getInteger("id"));
            if (delconsult!=0){
                result.setCode(0);
                result.setMessage("删除会诊成功");
            }else {
                result.setCode(1);
                result.setMessage("删除会诊失败，检查是否有这个消息");
            }
        }else {
            result.setCode(1);
            result.setMessage("没有这个消息");
        }

        return result;
    }

}
